package com.tuoyu.peopletest.device;

import android.widget.EditText;

import com.stresscube.usbdevice.USBDevicePDHIDWithAddress;
import com.tuoyu.peopletest.R;

public class DeviceName_old {
    private final byte[] version={0x01, 0x02};
    private final int nDataBytes=34, address=7, nNameMaxLen=16, nNoMaxLen=16;
    private String strName;
    private String strNo;

    public String getStrName() {
        return strName;
    }

    public void setStrName(String strName) {
        this.strName = strName;
    }

    public String getStrNo() {
        return strNo;
    }

    public void setStrNo(String strNo) {
        this.strNo = strNo;
    }

    public void setData(String strName, String strNo) {
        this.strName=strName;
        this.strNo=strNo;
    }
    private int getStringLen(byte[] data, int iStart, int maxLen) {
        if(iStart>=data.length)
            return -1;
        for(int i=0;i<maxLen;i++) {
            if(data[iStart+i]==0)
                return i;
        }
        return maxLen;
    }
    public boolean readNameFromDevice(USBDevicePDHIDWithAddress device) {
        byte[] data=new byte[nDataBytes];
        if(!device.ReadMemoBlock(address, data))
            return false;

        int iData=0;
        if(data[iData]!=version[0]||data[iData+1]!=version[1])
            return false;

        iData+=2;
        int len=getStringLen(data, iData, nNameMaxLen);
        if(len<=0)
            return false;
        byte[] name=new byte[len];
        System.arraycopy(data, iData, name, 0, len);
        String strName=new String(name);

        iData+=nNameMaxLen;
        len=getStringLen(data, iData, nNoMaxLen);
        if(len<=0)
            return false;
        byte[] no=new byte[len];
        System.arraycopy(data, iData, no, 0, len);
        String strNo=new String(no);

        this.strName=strName;
        this.strNo=strNo;
        return true;
    }

    public boolean writeNameToDevice(USBDevicePDHIDWithAddress device) {
        try {
            byte[] data = new byte[nDataBytes];
            int iData = 0;
            data[iData] = version[0];
            data[iData + 1] = version[1];
            iData += 2;

            byte[] name=strName.getBytes();
            int len=name.length<nNameMaxLen?name.length:nNameMaxLen;
            System.arraycopy(name,0,data, iData, len);
            iData+=16;

            byte[] no=strNo.getBytes();
            len=no.length<nNoMaxLen?no.length:nNoMaxLen;
            System.arraycopy(no,0,data, iData, len);

            if (device.WriteMemoBlock(address, data))
                return true;
            return false;
        }catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
